//
//  ICChatBox.m
//  ICome
//
//  Created by ENN on 16/3/10.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatBox.h"
#import "UIImage+Extension.h"
#import "ICEmotion.h"

#define TopMargin 5

@interface ICChatBox ()<UITextViewDelegate>

/** chotBox的顶部边线 */
@property (nonatomic, strong) UIView *topLine;
/** 录音按钮 */
@property (nonatomic, strong) UIButton *voiceButton;
/** 表情按钮 */
@property (nonatomic, strong) UIButton *faceButton;
/** (+)按钮 */
@property (nonatomic, strong) UIButton *moreButton;
/** 按住说话 */
@property (nonatomic, strong) UIButton *talkButton;
@property (nonatomic, strong)UIButton *pubBtton;

@property (nonatomic, assign)float pubMenuWidth;

@end

@implementation ICChatBox


- (id) initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.status = ICChatBoxStatusNothing; // 起始状态
//        [self setBackgroundColor:MENU_BACKGROUND_COLOR];
        [self setBackgroundColor:[UIColor whiteColor]];
        self.pubMenuWidth = 5;
//        [self addNotification];
    }
    return self;
}

-(void)setGroup:(ICGroup *)group {
    _group = group;
    if ([group.gId isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) {
        self.pubMenuWidth = 37;
        [self addSubview:self.pubBtton];
    }
    
    [self addSubview:self.topLine];
    [self addSubview:self.voiceButton];
    [self addSubview:self.textView];
    [self addSubview:self.faceButton];
    [self addSubview:self.moreButton];
    [self addSubview:self.talkButton];
}

#pragma mark - UITextViewDelegate

- (void) textViewDidBeginEditing:(UITextView *)textView
{
//    ICChatBoxStatus lastStatus = self.status;
    self.status = ICChatBoxStatusShowKeyboard;
//    [self setTextViewSizeToFit:NO];
}

- (void) textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 5000) { // 限制5000字内
        textView.text = [textView.text substringToIndex:5000];
    }
    
    
    CGRect line = [_textView caretRectForPosition:
                   _textView.selectedTextRange.start];
    CGFloat overflow = line.origin.y + line.size.height - (_textView.contentOffset.y + _textView.bounds.size.height - _textView.contentInset.bottom - _textView.contentInset.top);
    if ( overflow > 0 ) {
        // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
        // Scroll caret to visible area
        CGPoint offset = _textView.contentOffset;
        offset.y += 4; // leave 5 pixels margin
        // Cannot animate with setContentOffset:animated: or caret will not appear
        [UIView animateWithDuration:.2 animations:^{
            [_textView setContentOffset:offset];
        }];
    }
   
    [self setTextViewSizeToFit:NO];
}

// 设置textview高度 status为默认高度
- (void)setTextViewSizeToFit:(BOOL)status {
    CGFloat maxHeight = MAX_TEXTVIEW_HEIGHT;
    CGFloat minHeight = [ICTools getChatBoxInputTextViewHeight];
    CGRect frame = self.textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [self.textView sizeThatFits:constraintSize];
    self.textView.textContainerInset = UIEdgeInsetsMake(10,0, 10, 0);
    if (size.height <= minHeight) {
        size.height = minHeight;
    } else {
        if (size.height >= maxHeight)
        {
            size.height = maxHeight;
            self.textView.scrollEnabled = YES;   // 允许滚动
//            self.textView.textContainerInset = UIEdgeInsetsMake(10,0, 10, 0);
        }
        else
        {
            self.textView.scrollEnabled = NO;    // 不允许滚动
        }
    }
   
    if (status) {
        size.height = minHeight;
    }
    self.textView.frame = CGRectMake(frame.origin.x, TopMargin, frame.size.width, size.height);
    if ([self.delegate respondsToSelector:@selector(chatBox:changeChatBoxHeight:)]) {
        [self.delegate chatBox:self changeChatBoxHeight:size.height + ([ICTools getChatBoxInputHeight] - [ICTools getChatBoxInputTextViewHeight])];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        if (self.textView.text.length > 0) {     // send Text
            if ([self.textView.text isTrimmingSpace]) {
                [MBProgressHUD showError:@"不能发送空白消息"];
            } else {
                if (_delegate && [_delegate respondsToSelector:@selector(chatBox:sendTextMessage:)]) {
                    [_delegate chatBox:self sendTextMessage:self.textView.text];
                }
            }
        }
        [self.textView setText:@""];
        [self setTextViewSizeToFit:YES];
        return NO;
    }
    if ([text isEqualToString:@"@"]) {
        [self routerEventWithName:GXRouterEventNoticeMy userInfo:@{}];
        NSLog(@"输入@");
        
    }
    
    if(text.length == 0 && range.length == 1) //删除
    { // 用于针对删除表情特殊字符串处理
        // 1.特殊情况长按调用系统UIMenuController只选择一个字符串删除
        if (textView.selectedRange.length == 1) { // 选定的文本长度
            return YES;
            
        }
        NSInteger loction = textView.selectedRange.location;// 获取光标位置
        NSString *frontContent = [textView.text substringToIndex:loction];// 获取光标位置前的字符串
        // 字符串以结尾比较,存在“\u2005”
        if ([frontContent hasSuffix:@"\u2005"])
        {
            NSInteger deletelength = 0;
            for(int i=0; i<frontContent.length; i++){
                unichar ch = [frontContent characterAtIndex: i];
                if(ch == '@')
                {
                    NSLog(@"位置 = %D",i);
                    deletelength = frontContent.length-i;
                }
            }
            NSLog(@"deletelength = %ld",deletelength);
            NSString *string = [frontContent substringToIndex:loction - deletelength];// 将获取的光标位置前的字符串删减表情特殊字符串（四个字符）
            NSString *backContent = [textView.text substringFromIndex:loction];// 获取光标位置后的字符串
            if (backContent.length > 0) {
                // 拼接删除字符后的字符串
                textView.text = [string stringByAppendingString:backContent];
            }else
                textView.text = string;
            return NO;
        }
        else
            return YES;
    }
    return YES;
}


#pragma mark - Public Methods

- (BOOL)resignFirstResponder
{
    [self.textView resignFirstResponder];
    [_moreButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_selector_N"] forState:UIControlStateNormal];
    [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_emotion_N"] forState:UIControlStateNormal];
    return [super resignFirstResponder];
}




#pragma mark - Event Response
- (void)pubButtonDown:(UIButton *)sender {
    ICChatBoxStatus lastStatus = self.status;
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        [_delegate chatBox:self changeStatusForm:lastStatus to:ICChatBoxStatusNothing];
    }
}

// 录音按钮点击事件
- (void) voiceButtonDown:(UIButton *)sender
{
    ICChatBoxStatus lastStatus = self.status;
    if (lastStatus == ICChatBoxStatusShowVoice || ![self.talkButton isHidden]) {//正在显示talkButton，改为键盘状态
        self.status = ICChatBoxStatusShowKeyboard;
        [self.talkButton setHidden:YES];
        [self.textView setHidden:NO];
        [self.textView becomeFirstResponder];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
    } else {    // 变成talkButton的状态
        self.status = ICChatBoxStatusShowVoice;
        [self.textView resignFirstResponder];
        [self.textView setHidden:YES];
        [self.talkButton setHidden:NO];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_keyboard_N"] forState:UIControlStateNormal];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
    }
    if (![self.textView isFirstResponder]) {
        [self setTextViewSizeToFit:YES];
    }
}

// 更多（+）按钮
- (void) moreButtonDown:(UIButton *)sender
{
    ICChatBoxStatus lastStatus = self.status;
    if (lastStatus == ICChatBoxStatusShowMore) { // 当前显示的就是more页面
        self.status = ICChatBoxStatusShowKeyboard;
        [self.textView becomeFirstResponder];
    } else {
        [self.talkButton setHidden:YES];
        [self.textView setHidden:NO];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
        
        self.status = ICChatBoxStatusShowMore;
        if (lastStatus == ICChatBoxStatusShowFace) {  // 改变按钮样式
            [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_emotion_N"] forState:UIControlStateNormal];
        } else if (lastStatus == ICChatBoxStatusShowVoice) {
            [_talkButton setHidden:YES];
            [_textView setHidden:NO];
            [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
        } else if (lastStatus == ICChatBoxStatusShowKeyboard) {
            [self.textView resignFirstResponder];
            self.status = ICChatBoxStatusShowMore;
        }
    }
    // 操作逻辑 先改变状态 再高变高度
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
    }
    [self setTextViewSizeToFit:NO];
}

// 表情按钮
- (void) faceButtonDown:(UIButton *)sender
{
    ICChatBoxStatus lastStatus = self.status;
    if (lastStatus == ICChatBoxStatusShowFace) {       // 正在显示表情,改为现实键盘状态
        self.status = ICChatBoxStatusShowKeyboard;
        [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_emotion_N"] forState:UIControlStateNormal];
        [self.textView becomeFirstResponder];
        [self.textView setHidden:NO];
    } else {
        [self.talkButton setHidden:YES];
        [self.textView setHidden:NO];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
        self.status = ICChatBoxStatusShowFace;
        [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_keyboard_N"] forState:UIControlStateNormal];
        if (lastStatus == ICChatBoxStatusShowMore) {
        } else if (lastStatus == ICChatBoxStatusShowVoice) {
             [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
            [_talkButton setHidden:YES];
            [_textView setHidden:NO];
        }  else if (lastStatus == ICChatBoxStatusShowKeyboard) {
            [self.textView resignFirstResponder];
            self.status = ICChatBoxStatusShowFace;
        } else if (lastStatus == ICChatBoxStatusShowVoice) {
            [self.talkButton setHidden:YES];
            [self.textView setHidden:NO];
            [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
            self.status         = ICChatBoxStatusShowFace;
        }
    }
    // 操作逻辑 先改变状态 再高变高度
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
    }
    [self setTextViewSizeToFit:NO];
}

// 说话按钮
- (void)talkButtonDown:(UIButton *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxDidStartRecordingVoice:)]) {
        [_delegate chatBoxDidStartRecordingVoice:self];
    }
}

- (void)talkButtonUpInside:(UIButton *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxDidStopRecordingVoice:)]) {
        [_delegate chatBoxDidStopRecordingVoice:self];
    }
}

- (void)talkButtonUpOutside:(UIButton *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxDidCancelRecordingVoice:)]) {
        [_delegate chatBoxDidCancelRecordingVoice:self];
    }
}

- (void)talkButtonTouchCancel:(UIButton *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(chatBoxDidCancelRecordingVoice:)]) {
        [_delegate chatBoxDidCancelRecordingVoice:self];
    }
}

- (void)talkButtonDragOutside:(UIButton *)sender
{
    if ([_delegate respondsToSelector:@selector(chatBoxDidDrag:)]) {
        [_delegate chatBoxDidDrag:NO];
    }
}

- (void)talkButtonDragInside:(UIButton *)sender
{
    if ([_delegate respondsToSelector:@selector(chatBoxDidDrag:)]) {
        [_delegate chatBoxDidDrag:YES];
    }
}

#pragma mark - Private

- (void)emotionDidSelected:(NSNotification *)notifi
{
    ICEmotion *emotion = notifi.userInfo[GXSelectEmotionKey];
    if (emotion.code) {
        [self.textView insertText:emotion.code.emoji];
        [self.textView scrollRangeToVisible:NSMakeRange(self.textView.text.length, 0)];
    } else if (emotion.face_name) {
        [self.textView insertText:emotion.face_name];
    }
}

// 删除表情
- (void)deleteBtnClicked
{

    if ([self.textView.text hasSuffix:@"\u2005"])
    {   /** 删除 @*/
        NSInteger deletelength = 0;
        for(int i=0; i<self.textView.text.length; i++){
            unichar ch = [self.textView.text characterAtIndex: i];
            if(ch == '@')
            {
                NSLog(@"位置 = %D",i);
                deletelength = self.textView.text.length-i;
            }
        }
         NSInteger loction = self.textView.selectedRange.location;// 获取光标位置
        NSString * string = [self.textView.text substringToIndex:loction - deletelength];// 将获取的光标位置前的字符串删减表情特殊字符串（四个字符）
        NSString *backContent = [self.textView.text substringFromIndex:loction];// 获取光标位置后的字符串
        if (backContent.length > 0) {
            // 拼接删除字符后的字符串
            self.textView.text = [string stringByAppendingString:backContent];
        }
        else
            self.textView.text = string;
    
    }else
    {/** 删除 表情*/
        [self.textView deleteBackward];
    }
}

- (void)sendMessage
{
    NSLog(@"sendMessage");
    if (self.textView.text.length > 0) {     // send Text
        if (_delegate && [_delegate respondsToSelector:@selector(chatBox:sendTextMessage:)]) {
            [_delegate chatBox:self sendTextMessage:self.textView.text];
        }
    }
    [self.textView setText:@""];
    [self setTextViewSizeToFit:YES];
}

-(void)addMessage:(NSDictionary *)dict
{NSLog(@"addMessage");
    [self.textView insertText:dict[@"nName"]];
    [self.textView scrollRangeToVisible:NSMakeRange(self.textView.text.length, 0)];

}

// 监听通知
- (void)addNotification
{
    NSLog(@"看看了几次消息addNotification");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionDidSelected:) name:GXEmotionDidSelectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteBtnClicked) name:GXEmotionDidDeleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendMessage) name:GXEmotionDidSendNotification object:nil];
    
}

- (void)removeNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - Getter and Setter

- (UIView *) topLine
{
    if (_topLine == nil) {
        _topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 0.5)];
//        [_topLine setBackgroundColor:IColor(165, 165, 165)];
    }
    return _topLine;
}

- (UIButton *) pubBtton
{
    if (!_pubBtton) {
        _pubBtton = [[UIButton alloc] initWithFrame:CGRectMake(0, TopMargin, self.pubMenuWidth, CHATBOX_BUTTON_WIDTH)];
        [_pubBtton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_keyboard_hide"] forState:UIControlStateNormal];
        [_pubBtton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_keyboard_hide"] forState:UIControlStateHighlighted];
        [_pubBtton addTarget:self action:@selector(pubButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pubBtton;
}

- (UIButton *) voiceButton
{
    if (_voiceButton == nil) {
        _voiceButton = [[UIButton alloc] initWithFrame:CGRectMake(self.pubMenuWidth, TopMargin, CHATBOX_BUTTON_WIDTH, CHATBOX_BUTTON_WIDTH)];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_N"] forState:UIControlStateNormal];
        [_voiceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_input_voice_HL"] forState:UIControlStateHighlighted];
        [_voiceButton addTarget:self action:@selector(voiceButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceButton;
}

- (UIButton *) moreButton
{
    if (_moreButton == nil) {
        _moreButton = [[UIButton alloc] initWithFrame:CGRectMake(App_Frame_Width - CHATBOX_BUTTON_WIDTH-5, TopMargin, CHATBOX_BUTTON_WIDTH, CHATBOX_BUTTON_WIDTH)];
        [_moreButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_selector_N"] forState:UIControlStateNormal];
        [_moreButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_selector_HL"] forState:UIControlStateHighlighted];
        [_moreButton addTarget:self action:@selector(moreButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreButton;
}

- (UIButton *) faceButton
{
    if (_faceButton == nil) {
        _faceButton = [[UIButton alloc] initWithFrame:CGRectMake(self.moreButton.x - CHATBOX_BUTTON_WIDTH, TopMargin, CHATBOX_BUTTON_WIDTH, CHATBOX_BUTTON_WIDTH)];
        [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_emotion_N"] forState:UIControlStateNormal];
        [_faceButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_toolView_emotion_HL"] forState:UIControlStateHighlighted];
        [_faceButton addTarget:self action:@selector(faceButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _faceButton;
}

- (ICChatBoxTextView *) textView
{
    if (_textView == nil) {
        _textView = [[ICChatBoxTextView alloc] initWithFrame:self.talkButton.frame];
        [_textView setFont:[UIFont systemFontOfSize:16]];
//        [_textView.layer setMasksToBounds:YES];
//        [_textView.layer setCornerRadius:5.0f];
//        [_textView.layer setBorderWidth:0.5f];
//        [_textView.layer setBorderColor:self.topLine.backgroundColor.CGColor];
        _textView.placeholder = @"请输入内容...";
        _textView.placeholderColor = ICRGB(0xc9c9c9);
        [_textView setScrollsToTop:NO];
        [_textView setReturnKeyType:UIReturnKeySend];
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.layoutManager.allowsNonContiguousLayout = NO;
        //        [_textView scrollRangeToVisible:NSMakeRange(_textView.text.length-1, 1)];
        _textView.textContainerInset = UIEdgeInsetsMake(10,0, 10, 0);
        [_textView setTextAlignment:NSTextAlignmentLeft];
//                _textView.contentOffset = CGPointMake(0, _textView.contentSize.height - _textView.frame.size.height - 10);
        [_textView setDelegate:self];
    }
    return _textView;
}

- (UIButton *) talkButton
{
    if (_talkButton == nil) {
        _talkButton = [[UIButton alloc] initWithFrame:CGRectMake(self.voiceButton.x + self.voiceButton.width + 5, TopMargin, self.faceButton.x - self.voiceButton.x - self.voiceButton.width - 8, [ICTools getChatBoxInputTextViewHeight])];
        [_talkButton setTitle:@"按住说话" forState:UIControlStateNormal];
        [_talkButton setTitle:@"松开结束" forState:UIControlStateHighlighted];
        [_talkButton setTitleColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0] forState:UIControlStateNormal];
        //高亮状态
//        [_talkButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:0.5]] forState:UIControlStateHighlighted];
        _talkButton.backgroundColor = [UIColor whiteColor];
        [_talkButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
//        [_talkButton.layer setMasksToBounds:YES];
//        [_talkButton.layer setCornerRadius:4.0f];
//        [_talkButton.layer setBorderWidth:0.5f];
//        [_talkButton.layer setBorderColor:self.topLine.backgroundColor.CGColor];
        [_talkButton setHidden:YES];
        [_talkButton addTarget:self action:@selector(talkButtonDown:) forControlEvents:UIControlEventTouchDown];
        [_talkButton addTarget:self action:@selector(talkButtonUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_talkButton addTarget:self action:@selector(talkButtonUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
        [_talkButton addTarget:self action:@selector(talkButtonTouchCancel:) forControlEvents:UIControlEventTouchCancel];
        [_talkButton addTarget:self action:@selector(talkButtonDragOutside:) forControlEvents:UIControlEventTouchDragOutside];
        [_talkButton addTarget:self action:@selector(talkButtonDragInside:) forControlEvents:UIControlEventTouchDragInside];
    }
    return _talkButton;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
